#!/bin/sh

ACTION="$1"

set -eux

. .travis/cmake-freebsd-env.sh

travis_install() {
  . .travis/cmake-freebsd-install.sh

  OLD_PWD="$PWD"

  mkdir -p /opt/freebsd/cache
  cd /opt/freebsd/cache

  # Extract the cached image
  tar -Sxzvf "$IMAGE_NAME.tgz"

  # Get the image we will be using out of the cached directory
  mv "$IMAGE_NAME" ..
  ls -lh

  cd ..

  ls -lh

  # === Get VM ready to build the code ===

  start_vm

  # Display FreeBSD kernel info and last login
  RUN uname -a
  RUN last

  cd "$OLD_PWD"

  # Copy over toxcore code from Travis to qemu
  scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -P $SSH_PORT -r ./* root@localhost:~

  RUN ls -lh
}

travis_script() {
  CACHEDIR="none"
  . ".travis/flags-$CC.sh"

  add_ld_flag -Wl,-z,defs

  # Make compilation error on a warning
  add_flag -Werror

  RUN 'cmake -B_build -H. \
    -DCMAKE_C_FLAGS="$C_FLAGS" \
    -DCMAKE_CXX_FLAGS="$CXX_FLAGS" \
    -DCMAKE_EXE_LINKER_FLAGS="$LD_FLAGS" \
    -DCMAKE_SHARED_LINKER_FLAGS="$LD_FLAGS" \
    -DCMAKE_INSTALL_PREFIX:PATH="_install" \
    -DTRACE=ON \
    -DMUST_BUILD_TOXAV=ON \
    -DSTRICT_ABI=ON \
    -DTEST_TIMEOUT_SECONDS=120 \
    -DUSE_IPV6=OFF'

  # We created the VM with the same number of cores as the host, so the host-ran `nproc` here is fine
  RUN 'gmake "-j$NPROC" -k install -C_build'
  RUN 'gmake "-j$NPROC" test ARGS="-j50" -C_build || \
    gmake "-j$NPROC" -C_build test ARGS="-j50 --rerun-failed" CTEST_OUTPUT_ON_FAILURE=1 || \
    true'
}

if [ "-z" "$ACTION" ]; then
  "travis_script"
else
  "travis_$ACTION"
fi
